<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
var echarts = require('echarts/lib/echarts')
// 引入 ECharts 主模块
require('echarts/lib/chart/line')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/legend')
// require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { themeColor } from '@/assets/echarts/theme'

export default {
  name: 'FifteenEcharts',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    fifteenDate: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    fifteenValue: function() {
      return this.fifteenDate.map(v => v.count)
    },
    fifteenLabel: function() {
      return this.fifteenDate.map(v => v.alarmType)
    }
  },
  watch: {
    fifteenDate: {
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'themeColor')
      this.chart.setOption({
        color: themeColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'line' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.fifteenLabel,
          axisLabel: {
            rotate: -20
          }
        },
        yAxis: {
          type: 'value'
        },
        grid: {
          left: '4%'
        },
        series: [{
          data: this.fifteenValue,
          type: 'line',
          smooth: true
        }]
      })
    }
  }
}
</script>
